<template>
  <a-card :bordered="false" :bodyStyle="{ padding: '0' }">
    <!-- table区域-begin -->
    <div>
      <a-table
        ref="table"
        size="middle"
        :scroll="{ x: true }"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="false"
        :loading="loading"
        class="j-table-force-nowrap"
        @change="handleTableChange">
        <template slot="status" slot-scope="status">
          <a-badge :status="status | statusTypeFilter" :text="status | statusFilter" />
        </template>
        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img
            v-else
            :src="getImgView(text)"
            height="25px"
            alt=""
            style="max-width:80px;font-size: 12px;font-style: italic;" />
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button v-else icon="download" @click="viewFile(text)">文件列表</a-button>
        </template>

        <span slot="action" slot-scope="text, record">
          <template v-if="!disabledButton">
            <a-button
              class="ruleButton"
              :ghost="true"
              type="primary"
              icon="edit"
              @click="handleEdit(record)"
              :disabled="isDisabledAuth('erpEmployeeTraining:edit')" />
            <a-divider type="vertical" />
            <a-popconfirm title="确定删除吗?" @confirm="() => listDelete(record.id)">
              <a-button
                class="ruleButton"
                :ghost="true"
                type="primary"
                icon="delete"
                :disabled="isDisabledAuth('erpEmployeeTraining:delete')" />
            </a-popconfirm>
          </template>
        </span>

      </a-table>
    </div>
    <view-file-modal ref="viewFileModal"></view-file-modal>
  </a-card>
</template>

<script>

import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { DisabledAuthFilterMixin } from '@/mixins/DisabledAuthFilterMixin'
import { viewFile } from '@/utils/util'
import ViewFileModal from '@/views/scy/components/ViewFileModal'
import { getAction } from '@/api/manage'
import moment from 'moment'
import { mapGetters } from 'vuex';
export default {
  name: 'HrErpEmployeeTrainingList',
  mixins: [JeecgListMixin, mixinDevice, DisabledAuthFilterMixin, viewFile],
  components: {
    ViewFileModal
  },
  props: {
    employeeId: {
      type: String,
      default: ''
    },
    resignTime: {
      type: String,
      default: ''
    },
    newData: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      description: '离职申请-培训扣款列表',
      isorter: {
        column: 'createTime',
        order: 'asc'
      },
      // 表头
      columns: [],
      // 列设置
      settingColumns: [],
      // 列定义
      defColumns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          }
        },
        {
          title: '培训开始日期',
          align: 'center',
          dataIndex: 'beginDate',
          customRender: function (text) {
            return !text ? '' : (text.length > 10 ? text.substr(0, 10) : text)
          }
        },
        {
          title: '培训结束日期',
          align: 'center',
          dataIndex: 'endDate',
          customRender: function (text) {
            return !text ? '' : (text.length > 10 ? text.substr(0, 10) : text)
          }
        },
        {
          title: '培训机构',
          align: 'center',
          dataIndex: 'institution'
        },
        {
          title: '培训项目',
          align: 'center',
          dataIndex: 'project'
        },
        {
          title: '取得证书名称',
          align: 'center',
          dataIndex: 'certificate'
        },
        {
          title: '培训服务期限',
          align: 'center',
          dataIndex: 'trainingServiceLimit_dictText'
        },
        {
          title: '服务期限起止时间',
          align: 'center',
          dataIndex: 'serviceStartDate',
          customRender: function (text, record) {
            console.log('record', record)
            return record.serviceStartDate + '~' + record.serviceEndDate
          }
        },
        {
          title: '培训费用(元)',
          align: 'center',
          dataIndex: 'trainingFee'
        },
        {
          title: '剩余应扣款(元)',
          align: 'center',
          dataIndex: 'remainingDeductions'
        }
      ],
      url: {
        list: '',
        delete: '/api/erp/files/employee/erpEmployeeTraining/delete',
        deleteBatch: '/api/erp/files/employee/erpEmployeeTraining/deleteBatch',
        exportXlsUrl: '/api/erp/files/employee/erpEmployeeTraining/exportXls',
        exportXlsUrl0: '/api/erp/files/employee/erpEmployeeTraining/exportXls?employeeId=',
        importExcelUrl: 'api/erp/files/employee/erpEmployeeTraining/importExcel'
      },
      mainId: '',
      dictOptions: {},
      superFieldList: []
    }
  },
  watch: {
    resignTime(newValue) {
      if (newValue) {
        this.calculateRemainingAmount()
      }
    }
  },
  created() {
    this.getSuperFieldList();
    this.url.exportXlsUrl = this.url.exportXlsUrl0 + this.$route.params.id;
    this.url.importExcelUrl = this.url.importExcelUrl0 + this.$route.params.id;
    this.initColumns();
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
    }
  },
  methods: {
    ...mapGetters(['userInfo']),
    async loadData(arg) {
      if (!this.url.list) {
        return
      }
      // 加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      var params = {}
      // params.employeeId = this.userInfo().empId
      params.pageNo = 1
      params.pageSize = -1
      if (this.url.list == '/api/erp/files/employee/erpEmployeeTrainingResign/list') {
        params.mainId = this.mainId
      } else {
        params.employeeId = this.userInfo().empId
      }
      console.log('erpEmployeeTraining', this.url.list)
      this.loading = true
      return getAction(this.url.list, params).then(res => {
        if (res.success) {
          // update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          this.dataSource = res.result.records || res.result
          this.calculateRemainingAmount()
          if (res.result.total) {
            this.ipagination.total = res.result.total
          } else {
            this.ipagination.total = 0
          }
          // 判断是否当前页没有数据且不为第一页
          if (this.dataSource.length == 0 && this.ipagination.current != 1) {
            this.ipagination.current = this.ipagination.current - 1
            this.loadData(this.ipagination.current - 1);
          }
          // update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
        } else {
          this.dataSource = [];
          this.ipagination.total = 0
          this.$message.warning(res.message)
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false
      }).catch(err => {
        this.$message.warning(err.message)
      })
    },
    // 计算剩余应扣款
    calculateRemainingAmount() {
      if (this.dataSource && this.dataSource.length > 0) {
        this.dataSource.map(item => {
          // console.log('resignTime', this.resignTime)
          if (this.resignTime && item.serviceEndDate && item.serviceStartDate) {
            console.log('resignTime', this.resignTime)
            // 判断离职日期是否大于结束日期
            if (moment(this.resignTime).isAfter(item.serviceEndDate)) {
              item.remainingDeductions = '0.00'
              return item
            } else {
              // 离职日期小于开始日期
              if (moment(item.serviceStartDate).isAfter(this.resignTime)) {
                item.remainingDeductions = '0.00'
                return item
              }
              const diffInDays = moment(item.serviceEndDate).diff(moment(this.resignTime), 'days');
              console.log('diffInDays', diffInDays)
              item.remainingDeductions = ((diffInDays / Number(item.trainingServiceLimit || 0)) * (item.trainingFee || 0)).toFixed(2)
              return item
            }
          } else {
            item.remainingDeductions = '0.00'
            return item
          }
        })
      }
    },
    listDelete(id) {
      this.dataSource.forEach((val, index) => {
        if (val.id === id) {
          this.dataSource.splice(index, 1)
        }
      })
      this.$emit('delete', this.dataSource)
    },
    handleOk(val) {
      if (val.id) {
        let index = this.dataSource.findIndex(item => item.id === val.id)
        if (index > -1) {
          this.dataSource.splice(index, 1, val)
        }
      } else {
        this.dataSource.push({ id: parseInt((Math.random() * 1000000000)).toString(), ...val })
      }
      this.$emit('ok', this.dataSource)
    },
    initDictConfig() {
    },
    getSuperFieldList() {
      let fieldList = [];
      fieldList.push({ type: 'date', value: 'beginDate', text: '开始时间' })
      fieldList.push({ type: 'date', value: 'endDate', text: '结束时间' })
      fieldList.push({ type: 'string', value: 'institution', text: '培训机构', dictCode: '' })
      fieldList.push({ type: 'string', value: 'project', text: '项目', dictCode: '' })
      fieldList.push({ type: 'string', value: 'certificate', text: '证书', dictCode: '' })
      fieldList.push({ type: 'Text', value: 'attachment', text: '附件', dictCode: '' })
      fieldList.push({ type: 'string', value: 'employeeId', text: '员工id', dictCode: '' })
      this.superFieldList = fieldList
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
